package com.ushier.shop.fruits.controller;

import com.ushier.shop.fruits.bean.ResponseMessageBean;
import com.ushier.shop.fruits.bean.User;
import com.ushier.shop.fruits.dao.UserDAO;
import net.sf.json.JSONObject;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user/login")
public class UserLoginServlet extends HttpServlet {

    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        resp.setHeader("content-type","text/html;charset=UTF-8");
        PrintWriter out = resp.getWriter();

        User user = userDAO.get(username);
        if(null == user || !user.getPassword().equals(password)){
            ResponseMessageBean bean = ResponseMessageBean.error("用户名/密码错误");
            out.print(JSONObject.fromObject(bean));
            return;
        }
        HttpSession session = req.getSession();
        session.setAttribute("uid", user.getId());
        out.print(JSONObject.fromObject(ResponseMessageBean.success(user)));
    }
}
